<template>
  <div>
    <section >
      <div class="grid_box">
        <div>
          <h3>用户登录</h3>
        </div>
        <div class="form_box">
          <span class="key_name">用户名</span>
          <span class="input">
            <input type="text" v-model="user" required />
          </span>
          <span class="key_name">密码</span>
          <span class="input">
            <input type="password" v-model="pwd" required />
          </span>
          <span class="key_name">验证码</span>
          <div class="input checkPic_code">
            <div>
              <input type="text" v-model="pic_check" required />
            </div>
            <img class="check_pic" :src="this.pic_src" alt="验证码加载失败" />
          </div>
          <span class="form_tip">
            <span>
              <a href="#" @click="changePic">换一张</a>
            </span>
          </span>
        </div>
        <div>
          <span>自动登录</span>
          <input type="checkbox" name="auto_sign" v-model="auto_sign" />
        </div>
        <div class="submit_btn">
          <button @click="encode">登录</button>
        </div>
      </div>
    </section>
  </div>
</template>

<script>
import axios from "axios";
import CryptoJS from "crypto-js";
import { spawnKey,infoEncode } from "@/assets/infoEncode.js";
import {cookieValidCheck} from "@/assets/userState.js"
import "@/assets/css/form.css";

export default {
  name: "Login",
  props: ["client_id","pic_src"],
  data() {
    return {
      user: "",
      pwd: "",
      check_code: "",
      timestamp: "",
      passcode: "",
      pic_check: "",
      auto_sign:false
    }
  },
  computed: {
    input_limit(){ //用户名(查找非字母数字下划线)及密码规范性检测
      return Boolean(!/[^\w]/g.test(this.user)) && /^[\x21-\x7E]+$/g.test(this.pwd);
    }
  },
  methods: {
    inputCheck(){
      if (this.input_limit) {
        this.encode();
      }else{
        window.alert("填写信息不规范");
      }
    },
    encode() {
      var code = (this.pic_check).toLowerCase();
      let key_list = spawnKey(code);
      let se_key = key_list[0];
      let rand_code = key_list[1];
      let spawn_time = key_list[2];
      // console.log(se_key, rand_code, "生成结果");
      this.check_code = rand_code;
      this.timestamp = spawn_time;
      this.passcode = infoEncode(se_key,this.pwd);
      this.send();
    },
    send() {
      const requireA = axios.create({
        baseURL: "",
      });
      var post_info = {
        clientid: this.client_id,
        password: this.passcode,
        account: this.user,
        timestamp: this.timestamp,
        checkcode: this.check_code,
        autosign: Number(this.auto_sign)
      };
      requireA({
        url: "/apiLogin",
        method: "POST",
        data: post_info,
      }).catch(function (error) {
        if (error.response) {
          console.log('登录请求失败',error.response.status);
        } else {
          console.log('Error', error.message);
          console.log(error.config);
        }
      }).then((res)=>{
        if (!res){
          return
        }
        if (typeof res['data']!= 'string') {
          // 存储session
          var user_info = {
            'user':this.user,
            'clientid':this.client_id,
            'token':res['data']['userToken'],
            'grade':res['data']['grade'],
            'email':res['data']['mail']
          };
          console.log(user_info,'user-info')
          var string_info = JSON.stringify(user_info);
          sessionStorage.setItem(this.client_id, string_info);
          // 更新VueX状态
          this.$store.commit('userLogin',{'userName':this.user,'clientId':this.client_id,'token':res['data']['userToken'],'grade':res['data']['grade'],'email':res['data']['mail']});
          if (this.auto_sign) {
            // 保存自动登录
            let res_dict ={
              'user':this.user,
              'clientid':this.client_id,
              'token':res['data']['login']['token'],
              'endtime':res['data']['login']['endtime']
            };
            let info = JSON.stringify(res_dict);
            console.log('local cookie',res_dict,info);
            localStorage.setItem('autoLogin',info);
          }
          // window.location.href="/";
        }else{
          // console.log(res['data'],'response',typeof( res['data']));
          window.alert(res['data']);
        }
      });
    },
    changePic(){
      this.$parent.getPic();
    },
    autoLogin(){
      var info = JSON.parse(localStorage.getItem('autoLogin'));
      if (info) {
        console.log('获取到info',info);
        var client = this.client_id;
        let res = cookieValidCheck(info,client);
        if (res){
          window.alert(res);
        }else{
          console.log('cookie 有效')
          const requireA = axios.create({
            baseURL: "",
          });
          requireA({
            url: "/apiAutoSign",
            method: "POST",
            data: info,
          }).catch(function (error) {
            if (error.response) {
              console.log('自动登录请求失败',error.response.status);
            } else {
              console.log('Error', error.message);
              console.log(error.config);
            }
          }).then((res)=>{
            if (!res){
              return
            }
            if (typeof res['data']!= 'string') {
              // 存储session
              var user_info = {
                'user':info['user'],
                'clientid':this.client_id,
                'token':res['data']['userToken'],
                'grade':res['data']['grade'],
                'email':res['data']['mail'],
                'mailShow':res['data']['mailShow']
              };
              var string_info = JSON.stringify(user_info);
              sessionStorage.setItem(this.client_id, string_info);
              // 更新VueX状态
              this.user = info['user'];
              this.$store.commit('userLogin',[this.user,this.client_id,res['data']['userToken'],res['data']['grade']]);
            }else{
              localStorage.removeItem('autoLogin');
              window.alert(res['data']);
            }
          });
      }}
    },
  },
  created() {
    this.autoLogin();
  },
};
</script>

<!-- Add "scoped" attribute to limit CSS to this component only -->
<style scoped>
</style>
